package com.example.temp.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "http://localhost:8081", allowCredentials = "true")
public class FileUploadController {
    
    @Value("${file.upload.path:./images/}")
    private String uploadPath;
    
    @Value("${server.port:4041}")
    private String port;
    
    @PostConstruct
    public void init() {
        if (!uploadPath.endsWith(File.separator)) {
            uploadPath += File.separator;
        }
        
        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }
    
    @PostMapping("/image")
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                result.put("errno", 1);
                result.put("message", "上传文件不能为空");
                return result;
            }
            
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename != null ? 
                originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase() : "";
            
            if (!isImageFile(fileExt)) {
                result.put("errno", 1);
                result.put("message", "不支持的文件类型: " + fileExt);
                return result;
            }
            
            // 创建上传目录
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            String uploadDir = uploadPath + "questions" + File.separator + datePath.replace("/", File.separator);
            File dir = new File(uploadDir);
            
            if (!dir.exists() && !dir.mkdirs()) {
                result.put("errno", 1);
                result.put("message", "创建上传目录失败");
                return result;
            }
            
            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + fileExt;
            String filePath = dir.getAbsolutePath() + File.separator + newFileName;
            
            try {
                // 保存文件
                Path path = Paths.get(filePath);
                Files.write(path, file.getBytes());
            } catch (IOException e) {
                result.put("errno", 1);
                result.put("message", "保存文件失败: " + e.getMessage());
                return result;
            }
            
            // 构建访问URL - 使用相对路径，由前端处理完整URL
            String accessUrl = String.format("/questionPictures/%s/%s", 
                datePath.replace("\\", "/"), newFileName);
            
            // 返回 wangEditor 需要的格式
            result.put("errno", 0);
            Map<String, String> data = new HashMap<>();
            data.put("url", accessUrl);
            result.put("data", data);
            
            return result;
            
        } catch (Exception e) {
            result.put("errno", 1);
            result.put("message", "上传过程中发生错误: " + e.getMessage());
            return result;
        }
    }
    private boolean isImageFile(String fileExt) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};
        for (String ext : imageExtensions) {
            if (ext.equalsIgnoreCase(fileExt)) {
                return true;
            }
        }
        return false;
    }
}